<template>
  <div class="admin-appointment-records">
    <div class="page-header">
      <h2>用户预约记录管理</h2>
      <div class="header-actions">
        <el-button 
          v-if="hasPermission('admin:appointment:export')"
          type="success" 
          @click="exportRecords" 
          :loading="exportLoading"
        >
          <el-icon><Download /></el-icon>
          导出记录
        </el-button>
        <el-button @click="refreshData">
          <el-icon><Refresh /></el-icon>
          刷新数据
        </el-button>
      </div>
    </div>

    <!-- 搜索筛选区域 -->
    <div class="search-container">
      <el-card>
        <el-form :model="searchForm" label-width="100px" inline>
          <el-form-item label="用户名">
            <el-input 
              v-model="searchForm.username" 
              placeholder="请输入用户名"
              clearable
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item label="发型师">
            <el-input 
              v-model="searchForm.storeManagerName" 
              placeholder="请输入发型师名称"
              clearable
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item label="预约状态">
            <el-select 
              v-model="searchForm.status" 
              placeholder="请选择状态"
              clearable
              style="width: 150px"
            >
              <el-option label="待确认" :value="0" />
              <el-option label="已确认" :value="1" />
              <el-option label="已完成" :value="2" />
              <el-option label="已取消" :value="3" />
            </el-select>
          </el-form-item>
          <el-form-item label="套餐名称">
            <el-input 
              v-model="searchForm.packageName" 
              placeholder="请输入套餐名称"
              clearable
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item label="预约日期">
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              @change="handleDateRangeChange"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch" :loading="loading">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="resetSearch">
              <el-icon><RefreshLeft /></el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <!-- 数据统计卡片 -->
    <div class="stats-container">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="stats-card">
            <div class="stats-content">
              <div class="stats-icon pending">
                <el-icon><Clock /></el-icon>
              </div>
              <div class="stats-info">
                <div class="stats-number">{{ stats.pending }}</div>
                <div class="stats-label">待确认</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stats-card">
            <div class="stats-content">
              <div class="stats-icon confirmed">
                <el-icon><Check /></el-icon>
              </div>
              <div class="stats-info">
                <div class="stats-number">{{ stats.confirmed }}</div>
                <div class="stats-label">已确认</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stats-card">
            <div class="stats-content">
              <div class="stats-icon completed">
                <el-icon><CircleCheck /></el-icon>
              </div>
              <div class="stats-info">
                <div class="stats-number">{{ stats.completed }}</div>
                <div class="stats-label">已完成</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stats-card">
            <div class="stats-content">
              <div class="stats-icon cancelled">
                <el-icon><Close /></el-icon>
              </div>
              <div class="stats-info">
                <div class="stats-number">{{ stats.cancelled }}</div>
                <div class="stats-label">已取消</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 数据表格 -->
    <div class="table-container">
      <el-card>
        <el-table 
          :data="appointments" 
          v-loading="loading" 
          stripe
          @sort-change="handleSortChange"
        >
          <el-table-column prop="id" label="预约ID" width="80" />
          <el-table-column prop="username" label="用户名" width="120">
            <template #default="{ row }">
              <div class="user-info">
                <div class="username">{{ row.username }}</div>
                <div class="nickname" v-if="row.nickname">{{ row.nickname }}</div>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="storeManagerName" label="发型师" width="120" />
          <el-table-column prop="appointmentDate" label="预约日期" width="120" sortable="custom" />
          <el-table-column prop="appointmentTime" label="预约时间" width="120" />
          <el-table-column prop="packageName" label="套餐" width="150">
            <template #default="{ row }">
              <div v-if="row.packageName" class="package-info">
                <div class="package-name">{{ row.packageName }}</div>
                <div class="package-price">￥{{ row.packagePrice }}</div>
              </div>
              <span v-else class="no-package">-</span>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="预约状态" width="100">
            <template #default="{ row }">
              <el-tag :type="getStatusTagType(row.status)">
                {{ row.statusName }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="paymentStatus" label="支付状态" width="100">
            <template #default="{ row }">
              <el-tag :type="getPaymentTagType(row.paymentStatus)">
                {{ row.paymentStatusName }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" width="180" sortable="custom">
            <template #default="{ row }">
              {{ formatDateTime(row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="备注" width="200" show-overflow-tooltip />
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="{ row }">
              <el-button 
                size="small" 
                @click="viewDetail(row)"
              >
                查看详情
              </el-button>
              <el-button 
                v-if="row.status === 0 && hasPermission('admin:appointment:confirm')"
                type="success" 
                size="small" 
                @click="confirmAppointment(row)"
              >
                确认预约
              </el-button>
              <el-button 
                v-if="row.status === 1 && hasPermission('admin:appointment:complete')"
                type="primary" 
                size="small" 
                @click="completeAppointment(row)"
              >
                完成预约
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="pagination.page"
            v-model:page-size="pagination.size"
            :page-sizes="[10, 20, 50, 100]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>

    <!-- 预约详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="预约详情" width="600px">
      <div v-if="selectedAppointment" class="detail-content">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="预约ID">{{ selectedAppointment.id }}</el-descriptions-item>
          <el-descriptions-item label="用户名">{{ selectedAppointment.username }}</el-descriptions-item>
          <el-descriptions-item label="用户昵称">{{ selectedAppointment.nickname || '-' }}</el-descriptions-item>
          <el-descriptions-item label="发型师">{{ selectedAppointment.storeManagerName }}</el-descriptions-item>
          <el-descriptions-item label="预约日期">{{ selectedAppointment.appointmentDate }}</el-descriptions-item>
          <el-descriptions-item label="预约时间">{{ selectedAppointment.appointmentTime }}</el-descriptions-item>
          <el-descriptions-item label="套餐名称">{{ selectedAppointment.packageName || '-' }}</el-descriptions-item>
          <el-descriptions-item label="套餐价格">
            <span v-if="selectedAppointment.packagePrice">￥{{ selectedAppointment.packagePrice }}</span>
            <span v-else>-</span>
          </el-descriptions-item>
          <el-descriptions-item label="预约状态">
            <el-tag :type="getStatusTagType(selectedAppointment.status)">
              {{ selectedAppointment.statusName }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="支付状态">
            <el-tag :type="getPaymentTagType(selectedAppointment.paymentStatus)">
              {{ selectedAppointment.paymentStatusName }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="创建时间" :span="2">
            {{ formatDateTime(selectedAppointment.createTime) }}
          </el-descriptions-item>
          <el-descriptions-item label="更新时间" :span="2">
            {{ formatDateTime(selectedAppointment.updateTime) }}
          </el-descriptions-item>
          <el-descriptions-item label="备注" :span="2">
            {{ selectedAppointment.remark || '-' }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Download, Refresh, Search, RefreshLeft, Clock, Check, 
  CircleCheck, Close 
} from '@element-plus/icons-vue'
import { getAdminAppointmentPage, confirmAppointment as confirmAppointmentApi, completeAppointment as completeAppointmentApi } from '@/api/appointment'
import { usePermissions } from '@/stores/permission'

// 权限检查
const { hasPermission } = usePermissions()

// 数据状态
const loading = ref(false)
const exportLoading = ref(false)
const appointments = ref([])
const detailDialogVisible = ref(false)
const selectedAppointment = ref(null)
const dateRange = ref([])

// 搜索表单
const searchForm = reactive({
  username: '',
  storeManagerName: '',
  status: null,
  packageName: '',
  startDate: '',
  endDate: ''
})

// 分页信息
const pagination = reactive({
  page: 1,
  size: 20,
  total: 0
})

// 统计数据
const stats = reactive({
  pending: 0,
  confirmed: 0,
  completed: 0,
  cancelled: 0
})

// 加载预约记录
const loadAppointments = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.page,
      size: pagination.size,
      ...searchForm
    }
    
    const response = await getAdminAppointmentPage(params)
    if (response.code === 200) {
      appointments.value = response.data.records || []
      pagination.total = response.data.total || 0
      
      // 计算统计数据
      calculateStats()
    } else {
      ElMessage.error(response.message || '获取预约记录失败')
    }
  } catch (error) {
    console.error('获取预约记录失败:', error)
    ElMessage.error('获取预约记录失败')
  } finally {
    loading.value = false
  }
}

// 计算统计数据
const calculateStats = () => {
  stats.pending = appointments.value.filter(item => item.status === 0).length
  stats.confirmed = appointments.value.filter(item => item.status === 1).length
  stats.completed = appointments.value.filter(item => item.status === 2).length
  stats.cancelled = appointments.value.filter(item => item.status === 3).length
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  loadAppointments()
}

// 重置搜索
const resetSearch = () => {
  Object.assign(searchForm, {
    username: '',
    storeManagerName: '',
    status: null,
    packageName: '',
    startDate: '',
    endDate: ''
  })
  dateRange.value = []
  pagination.page = 1
  loadAppointments()
}

// 处理日期范围变化
const handleDateRangeChange = (dates) => {
  if (dates && dates.length === 2) {
    searchForm.startDate = dates[0]
    searchForm.endDate = dates[1]
  } else {
    searchForm.startDate = ''
    searchForm.endDate = ''
  }
}

// 分页处理
const handleSizeChange = (size) => {
  pagination.size = size
  pagination.page = 1
  loadAppointments()
}

const handleCurrentChange = (page) => {
  pagination.page = page
  loadAppointments()
}

// 排序处理
const handleSortChange = ({ column, prop, order }) => {
  // 这里可以添加排序逻辑
  console.log('Sort changed:', { column, prop, order })
}

// 查看详情
const viewDetail = (appointment) => {
  selectedAppointment.value = appointment
  detailDialogVisible.value = true
}

// 确认预约
const confirmAppointment = async (appointment) => {
  try {
    await ElMessageBox.confirm(
      `确定要确认预约 ${appointment.id} 吗？`,
      '确认操作',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const response = await confirmAppointmentApi(appointment.id)
    if (response.code === 200) {
      ElMessage.success('预约确认成功')
      loadAppointments()
    } else {
      ElMessage.error(response.message || '预约确认失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('确认预约失败:', error)
      ElMessage.error('确认预约失败')
    }
  }
}

// 完成预约
const completeAppointment = async (appointment) => {
  try {
    await ElMessageBox.confirm(
      `确定要完成预约 ${appointment.id} 吗？`,
      '完成预约',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const response = await completeAppointmentApi(appointment.id)
    if (response.code === 200) {
      ElMessage.success('预约完成成功')
      loadAppointments()
    } else {
      ElMessage.error(response.message || '预约完成失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('完成预约失败:', error)
      ElMessage.error('完成预约失败')
    }
  }
}

// 导出记录
const exportRecords = async () => {
  exportLoading.value = true
  try {
    // 这里可以调用导出API
    ElMessage.success('导出功能开发中...')
  } catch (error) {
    ElMessage.error('导出失败')
  } finally {
    exportLoading.value = false
  }
}

// 刷新数据
const refreshData = () => {
  loadAppointments()
}

// 获取状态标签类型
const getStatusTagType = (status) => {
  const tagTypes = {
    0: 'warning',   // 待确认
    1: 'success',   // 已确认
    2: 'primary',   // 已完成
    3: 'danger'     // 已取消
  }
  return tagTypes[status] || 'info'
}

// 获取支付状态标签类型
const getPaymentTagType = (paymentStatus) => {
  const tagTypes = {
    0: 'warning',   // 未支付
    1: 'success',   // 已支付
    2: 'danger'     // 支付失败
  }
  return tagTypes[paymentStatus] || 'info'
}

// 格式化日期时间
const formatDateTime = (dateTimeString) => {
  if (!dateTimeString) return '-'
  const date = new Date(dateTimeString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 初始化
onMounted(() => {
  loadAppointments()
})
</script>

<style scoped>
.admin-appointment-records {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #303133;
  font-size: 24px;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.search-container {
  margin-bottom: 20px;
}

.stats-container {
  margin-bottom: 20px;
}

.stats-card {
  height: 100px;
}

.stats-content {
  display: flex;
  align-items: center;
  height: 100%;
}

.stats-icon {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
  font-size: 24px;
  color: white;
}

.stats-icon.pending {
  background: linear-gradient(135deg, #ffa940, #ff7875);
}

.stats-icon.confirmed {
  background: linear-gradient(135deg, #52c41a, #73d13d);
}

.stats-icon.completed {
  background: linear-gradient(135deg, #1890ff, #40a9ff);
}

.stats-icon.cancelled {
  background: linear-gradient(135deg, #ff4d4f, #ff7875);
}

.stats-info {
  flex: 1;
}

.stats-number {
  font-size: 28px;
  font-weight: bold;
  color: #303133;
  line-height: 1;
  margin-bottom: 5px;
}

.stats-label {
  font-size: 14px;
  color: #909399;
}

.table-container {
  background: white;
  border-radius: 8px;
  overflow: hidden;
}

.user-info .username {
  font-weight: 500;
  color: #303133;
}

.user-info .nickname {
  font-size: 12px;
  color: #909399;
  margin-top: 2px;
}

.package-info .package-name {
  font-weight: 500;
  color: #303133;
}

.package-info .package-price {
  font-size: 12px;
  color: #f56c6c;
  margin-top: 2px;
}

.no-package {
  color: #c0c4cc;
}

.pagination-container {
  padding: 20px;
  text-align: right;
  border-top: 1px solid #ebeef5;
}

.detail-content {
  padding: 10px 0;
}

:deep(.el-table) {
  font-size: 14px;
}

:deep(.el-table th) {
  background-color: #fafafa;
  color: #606266;
  font-weight: 500;
}

:deep(.el-card__body) {
  padding: 20px;
}

:deep(.el-form--inline .el-form-item) {
  margin-bottom: 10px;
}
</style> 